package Staff

import (
	"ali-hr/Database"
	"ali-hr/Models"
	"fmt"
	"github.com/gookit/goutil/dump"
	"time"
)

/**
 * Created by Goland
 * User: wkk alisleepy@hotmail.com
 * Time: 2023/1/8 - 02:45
 * Desc: <员工离职操作相关>
 */

// ResignList 员工辞职申请列表
func ResignList(pageIndex, pageSize int, filters map[string]interface{}, all bool) ([]Models.StaffResign, int, error) {
	var staffResigns []Models.StaffResign
	var total = 0
	var Db = Database.SqlDB
	for k, val := range filters {
		if val == 0 || val == "" || val == nil {
			continue
		}
		// 雇佣状态
		if k == "status" {
			Db = Db.Where("status = ?", val)
		}
		if k == "name" {
			Db = Db.Where("name like ?", "%val%")
		}
	}
	// 是否获取所有
	if all == true {
		err := Db.Preload("Staff").Find(&staffResigns).Error
		if err != nil {
			return nil, 0, err
		}
	} else {
		// 分页操作，offset 和 limit
		err := Db.Preload("Staff").Offset((pageIndex - 1) * pageSize).
			Limit(pageSize).
			Find(&staffResigns).Error
		if err != nil {
			return nil, 0, err
		}
	}
	// 获取总数
	total = len(staffResigns)

	return staffResigns, total, nil
}

// DeleteStaffs 删除离职员工账号
func DeleteStaffs() {
	dump.P("删除员工定时任务测试。。。")
	// 获取当前已同意的辞职申请书
	staffResigns := getResignStaffs()
	if staffResigns == nil {
		return
	}

	// 修改员工信息为已离职
	for _, staffResign := range staffResigns {
		err := setStaffLeft(staffResign)
		if err != nil {
			continue
		}

		// 更新辞职申请表为已归档
		setStaffResignFinish(staffResign)
	}
}

// 获取当前已同意的并且当前到了离职日期的辞职申请书
func getResignStaffs() []Models.StaffResign {
	var staffResigns []Models.StaffResign
	err := Database.SqlDB.Where("status = ? and final_left_date <= ?", Models.RESIGN_STATUS_AGREED, time.Now().Format("2006-01-02")).Find(&staffResigns).Error
	if err != nil {
		dump.P("当前没有同意的辞职申请书")
		return nil
	}

	return staffResigns
}

// 修改员工信息为已离职
func setStaffLeft(staffResign Models.StaffResign) error {
	var staff Models.Staff
	err := Database.SqlDB.Where("id = ?", staffResign.StaffId).First(&staff).Error
	if err != nil {
		dump.P("未找到该员工，staff_id = ", staffResign.StaffId)
		return err
	}
	dump.P(fmt.Sprintf("【%s】已离职", staff.Name))

	// 更新离职日期和雇佣状态为已离职
	staff.Status = Models.DIMISSION
	staff.LeftDate = staffResign.FinalLeftDate
	staff.UpdatedAt = time.Now()
	Database.SqlDB.Save(staff)
	return nil
}

// 员工离职后，辞职申请状态改为归档
func setStaffResignFinish(staffResign Models.StaffResign) {
	staffResign.Status = Models.RESIGN_STATUS_FINISH
	staffResign.UpdatedAt = time.Now()
	Database.SqlDB.Save(staffResign)
}
